<template>
  <div class="admin-message-page">
    <el-card class="main-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><Message /></el-icon>
            <span class="header-title">留言管理</span>
          </div>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="keyword"
          placeholder="搜索留言内容..."
          clearable
          style="max-width: 300px;"
          @clear="loadList"
          @keyup.enter="loadList"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="loadList" :icon="Search">搜索</el-button>
        <el-button @click="handleReset" :icon="Refresh">重置</el-button>
      </div>

      <!-- 表格 -->
      <el-table 
        :data="list" 
        border 
        stripe
        v-loading="loading"
        style="width: 100%; margin-top: 20px;"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: '600' }"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="userName" label="用户" width="120" align="center">
          <template #default="{ row }">
            <span>{{ row.userName || row.nickname || '匿名用户' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="留言内容" min-width="300" show-overflow-tooltip>
          <template #default="{ row }">
            <span class="content-text">{{ row.content }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="reply" label="管理员回复" min-width="250" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.reply" class="reply-text">{{ row.reply }}</span>
            <el-tag v-else type="info" size="small" effect="plain">未回复</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="留言时间" width="180" align="center">
          <template #default="{ row }">
            <span class="time-text">{{ formatTime(row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button 
              size="small" 
              type="success" 
              @click="openReply(row)"
              :icon="Edit"
            >
              回复
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="del(row.id)"
              :icon="Delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态 -->
      <el-empty 
        v-if="!loading && list.length === 0" 
        description="暂无留言数据"
        style="margin: 40px 0;"
      />

      <!-- 回复对话框 -->
      <el-dialog 
        v-model="replyVisible" 
        title="回复留言" 
        width="600px"
        @close="handleDialogClose"
      >
        <div class="original-message">
          <div class="message-label">原始留言：</div>
          <div class="message-text">{{ currentMessage?.content }}</div>
        </div>
        <el-divider />
        <el-input 
          type="textarea" 
          v-model="replyText" 
          :rows="4"
          placeholder="请输入回复内容..."
          maxlength="500"
          show-word-limit
        />
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="replyVisible = false">取消</el-button>
            <el-button type="primary" @click="submitReply" :loading="replying">提交</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { Message, Search, Refresh, Edit, Delete } from "@element-plus/icons-vue";

const list = ref([]);
const keyword = ref("");
const loading = ref(false);
const replyVisible = ref(false);
const replyText = ref("");
const currentId = ref(null);
const currentMessage = ref(null);
const replying = ref(false);

const formatTime = (time) => {
  if (!time) return '-';
  if (typeof time === 'string' && time.includes('T')) {
    return time.replace('T', ' ').substring(0, 19);
  }
  return time;
};

const loadList = async () => {
  loading.value = true;
  try {
    const res = await axios.get("http://localhost:8080/api/message/admin/list", { 
      params: { keyword: keyword.value } 
    });
    if (res.data.code === 200) {
      list.value = res.data.data || [];
    } else {
      ElMessage.error(res.data.msg || '获取留言列表失败');
    }
  } catch (error) {
    console.error('加载留言列表失败:', error);
    ElMessage.error('加载留言列表失败');
  } finally {
    loading.value = false;
  }
};

const handleReset = () => {
  keyword.value = '';
  loadList();
};

const openReply = (row) => {
  currentId.value = row.id;
  currentMessage.value = row;
  replyText.value = row.reply || "";
  replyVisible.value = true;
};

const handleDialogClose = () => {
  replyText.value = "";
  currentId.value = null;
  currentMessage.value = null;
};

const submitReply = async () => {
  if (!replyText.value.trim()) {
    ElMessage.warning('请输入回复内容');
    return;
  }
  
  replying.value = true;
  try {
    const res = await axios.put("http://localhost:8080/api/message/admin/reply", null, {
      params: { id: currentId.value, reply: replyText.value.trim() },
    });
    if (res.data.code === 200) {
      ElMessage.success("回复成功");
      replyVisible.value = false;
      loadList();
    } else {
      ElMessage.error(res.data.msg || '回复失败');
    }
  } catch (error) {
    console.error('回复失败:', error);
    ElMessage.error('回复失败');
  } finally {
    replying.value = false;
  }
};

const del = async (id) => {
  try {
    await ElMessageBox.confirm("确定删除该留言吗？删除后无法恢复。", "提示", { 
      type: "warning",
      confirmButtonText: '确定删除',
      cancelButtonText: '取消'
    });
    
    const res = await axios.delete("http://localhost:8080/api/message/admin/delete", { 
      params: { id } 
    });
    if (res.data.code === 200) {
      ElMessage.success("删除成功");
      loadList();
    } else {
      ElMessage.error(res.data.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

onMounted(loadList);
</script>

<style scoped>
.admin-message-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100%;
}

.main-card {
  border-radius: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  font-size: 22px;
  color: #409eff;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.content-text,
.reply-text {
  color: #606266;
  font-size: 14px;
}

.time-text {
  color: #909399;
  font-size: 13px;
}

.original-message {
  margin-bottom: 16px;
}

.message-label {
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.message-text {
  padding: 12px;
  background: #f5f7fa;
  border-radius: 6px;
  color: #606266;
  line-height: 1.6;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table__header) {
  background: linear-gradient(135deg, #f5f7fa 0%, #e9ecef 100%);
}

:deep(.el-table__header th) {
  background: transparent !important;
  border-bottom: 2px solid #e4e7ed;
  padding: 18px 0;
}

:deep(.el-table__body tr:hover > td) {
  background-color: #f0f9ff !important;
}

:deep(.el-table__body td) {
  padding: 18px 0;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-table__row:hover) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
